package com.bdjk.bdmw.InfoGath.communication.server.tcp.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import org.apache.log4j.Logger;

import com.bdjk.bdmw.InfoGath.communication.dataProcess.DataProcess;

/**
 * @author hy
 * @description tcp通信线程，通过socket获取输入输出流，完成与客户端的交互
 *
 */
public class CommunicationThread implements Runnable{

	private static final Logger logger = Logger.getLogger(CommunicationThread.class);
	
	private Socket socket;
	
	public CommunicationThread(Socket socket) {
		this.socket = socket;
	}
	
	@Override
	public void run() {
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			inputStream = socket.getInputStream();
			outputStream = socket.getOutputStream();
			
			while(true){
				byte[] buffer = new byte[1024];

				int length = inputStream.read(buffer);
				// 客户端出来的消息（不能有回车换行）
				String msg = new String(buffer, 0, length);
				// 打印收到客户端发来的消息
				logger.info("Server--------" + msg + "---------");
				// 消息处理类
				DataProcess dataProcess  = new DataProcess();
				dataProcess.messageHandle(msg);
				// 如果当前协议是需要相应的，那么就给客户端发送消息
				if(dataProcess.protocol != null && dataProcess.isResponse){
					// 需要发送的消息
					outputStream.write(dataProcess.responseMsg.getBytes());
					logger.info("Resonse--------" + dataProcess.responseMsg + "---------");
				}
			}
			
		} catch (IOException e){
			
		} finally {
			try {
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
